package org.itboys.mobile.service.mongo.web;


import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.SundayPermission;
import org.itboys.mobile.service.mysql.web.product.SundayProductService;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_用户_service
 */
@Service
public class SundayMemberService extends BaseMongoService<SundayMember> {
    @Autowired
    private SundayUploadService uploadService;
  /*  @Autowired
    private ResourceHolder resourceHolder;*/
    @Autowired
    private SystemDictionaryService dictionaryService;
    @Autowired
    private SundayPermissionService permissionService;
    @Autowired
    private SundayProductService productService;
    @Resource(name = "mobileDs")
    private MongoDataSource mobileDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mobileDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }
    /**
     * 分页获取用户信息
     * @param request
     * @return
     */
    public PageResult<SundayMember> selectMember(HttpServletRequest request){
        Map<String,Object> param =ParamUtil.packageMongoExactParam(request,"userType","status","parentId","categoryId","isRmpp","isRqpp","isQlpp","isJppp","isBrandRecommend");
        param.put("isDeleted", 0);
        Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request,"nickName","mobileName","mobile");
        PageResult<SundayMember> pageResult=super.containpageQuery(request,containsparam,param);

        return pageResult;
    }
    /**
     * 分页获取用户信息
     * @param request
     * @return
     */
    public List<SundayMember> selectMemberNoPage(HttpServletRequest request,List<Integer> userTypes){
        Map<String,Object> param =ParamUtil.packageMongoExactParam(request,"userType");
        param.put("isDeleted", 0);
        param.put("parentId",0);
        if(ListUtil.isNotNull(userTypes)){
            param.put("userType in",userTypes);
        }
        return super.list(param);
    }

    /**
     * 修改或新增
     * @param member
     */
    public void saveMember(SundayMember member, MultipartFile imageFile,MultipartFile backImageFile) throws  Exception{
        Map<String,Object> param =new HashMap<String, Object>();
        if(member.getId()==0l){

            param.put("isDeleted",0);
            param.put("mobile",member.getMobile());
            if(ListUtil.isNotNull(super.list(param))){
                throw new ErrorException("手机号不能重复");
            }
            //生成默认头像
            Map<String, String> map = uploadService.uploadSingle(imageFile);
            if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
                member.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
            }else{
                member.setImage(NameUtil.getRandomLogo());
            }
            //生成背景图
            Map<String, String> backmap = uploadService.uploadSingle(backImageFile);
            if(StringUtils.isNotEmpty(backmap.get(uploadService.UPLOAD_HALF_PATH))){
                member.setBackImage(backmap.get(uploadService.UPLOAD_HALF_PATH));
            }
            if(StringUtils.isNotEmpty(member.getPassword())){
                member.setPassword(Digests.md5(member.getPassword()));
            }

            super.save(member);
        }else{
            Map<String, String> map = uploadService.uploadSingle(imageFile);
            if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
                member.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
            }
            //生成背景图
            Map<String, String> backmap = uploadService.uploadSingle(backImageFile);
            if(StringUtils.isNotEmpty(backmap.get(uploadService.UPLOAD_HALF_PATH))){
                member.setBackImage(backmap.get(uploadService.UPLOAD_HALF_PATH));
            }
            param.put("id !=",member.getId());
            param.put("isDeleted",0);
            param.put("mobile",member.getMobile());
            if(ListUtil.isNotNull(super.list(param))){
                throw new ErrorException("手机号不能重复");
            }
            if(StringUtils.isNotEmpty(member.getPassword())){
                member.setPassword(Digests.md5(member.getPassword()));
            }
            super.updateExceptEmpty(member.getId(),member);
        }
    }

    /**
     *  单个用户查询
     * @param id
     * @param userType
     * @return
     */
    public SundayMember findOne(Long id,Integer userType) {
        SundayMember member =null;
        if(LongUtil.isNotZreo(id)){
            member=super.getById(id);
        }else{
            member=new SundayMember();
            member.setId(0);
            member.setUserType(userType);
        }
        member.setPassword(null);
        return member;
  }
    /**
     * 重置为默认密码
     * @param id
     */
    public void resetPassword(Long id){
            super.update(id,"password",Digests.md5(SundayCommonConstants.default_password));

    }
    /**
     * 冻结或启用用户账号
     * @param id
     */
    public void changeStatus(Long id,Integer status){
        super.update(id,"status",status);
    }

    /**
     * 审核用户
     * @param id
     */
    public void handle(Long id){
        SundayMember member=super.getById(id);
        //如果用户状态不为新生成的也不为修改的状态
        if(member.getStatus()!=SundayCommonConstants.user_status_dsh&&member.getStatus()!=SundayCommonConstants.user_status_new){
            throw  new ErrorException("请勿重复操作");
        }
        member.setStatus(SundayCommonConstants.user_status_ytg);
        super.updateExceptEmpty(id,member);
    }
    public void set(Long id,Integer setType,Integer type){
        SundayMember member=super.getById(id);
        Map<String,Object> param=new HashMap<String,Object>();
        Long count=0l;
        //设置部分
        if(setType==1){
            if(type==1){
                param.clear();
                param.put("isDeleted",0);
                param.put("isRmpp",1);
                count=super.count(param);
                if(count>=18){
                    throw  new ErrorException("超过数量"+18);
                }
                member.setIsRmpp(1);
            }else if(type==2){
                param.clear();
                param.put("isDeleted",0);
                param.put("isRqpp",1);
                count=super.count(param);
                if(count>=18){
                    throw  new ErrorException("超过数量"+18);
                }
                member.setIsRqpp(1);

            }else if(type==3){
                param.clear();
                param.put("isDeleted",0);
                param.put("isQlpp",1);
                count=super.count(param);
                if(count>=18){
                    throw  new ErrorException("超过数量"+18);
                }
                member.setIsQlpp(1);
            }else if(type==4){
                param.clear();
                param.put("isDeleted",0);
                param.put("isJppp",1);
                count=super.count(param);
                if(count>=35){
                    throw  new ErrorException("超过数量"+35);
                }
                member.setIsJppp(1);
            }else if(type==5){
                member.setIsBrandRecommend(1);
            }else if(type==6){
                member.setIsBrandText(1);
            }
        }
        //取消设置
        if(setType==0){
            if(type==1){
                member.setIsRmpp(0);
            }else if(type==2){
                member.setIsRqpp(0);
            }else if(type==3){
                member.setIsQlpp(0);
            }else if(type==4){
                member.setIsJppp(0);
            }else if(type==5){
                member.setIsBrandRecommend(0);
            }else if(type==6){
                member.setIsBrandText(0);
            }
        }
        super.updateExceptEmpty(id,member);
    }

    /**
     * 同时删除用户和产品
     * @param memberId
     */
    public void deleteMemberRecordAndProduct(Long memberId){
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("memberId",memberId);
        List<SundayPermission> permissions=permissionService.list(param);
        for (SundayPermission sundayPermission :permissions) {
            productService.delete(sundayPermission.getOtherId());
        }
        super.delete(memberId);
        permissionService.delete(param);

    }
    /**
     * 组装用户标签
     */
    public List<SundayMember> packageTags(List<SundayMember> members,SundayMember member,String key,boolean isAll){
        if(ListUtil.isNull(members))members=new ArrayList<SundayMember>();
        if(member!=null) members.add(member);
        if(ListUtil.isNull(members))return members;
        //查询字段中所有的标签
        List<SystemDictionary> dictionaries=dictionaryService.getDictionaryByKey(key);
        for(SundayMember m:members){
            if(m.getTag()==null)m.setTag("");
            String [] tagIds = m.getTag().split(",");
            //默认有个0参数

            List<Map<String,Object>> tags = new ArrayList<Map<String, Object>>();
            for(SystemDictionary dictionary:dictionaries){
                Map<String,Object> tag=new HashMap<String,Object>();
                tag.put("id",dictionary.getId());
                tag.put("name",dictionary.getValue());
                int isChecked=0;

                for(String tagId:tagIds){
                    if(tagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
                        isChecked=1;
                        break;
                    }
                }
                tag.put("isChecked",isChecked);
                if(!isAll){
                    if(isChecked==1)tags.add(tag);
                }else{
                    tags.add(tag);
                }

            }
            m.setTags(tags);

        }
                return members;
    }

}
